package com;

import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import javax.swing.*;

import com.Communicator;
import com.Configurator;

public class Tray {
	public static void createAndShowGUI(TaskFinder taskFinder) {
		// Check the SystemTray support
		if (!SystemTray.isSupported()) {
			System.out.println("SystemTray is not supported");
			return;
		}
		final PopupMenu popup = new PopupMenu();
		final TrayIcon trayIcon = new TrayIcon(createImage("/sourse/bulb.gif",
				"tray icon"));
		final SystemTray tray = SystemTray.getSystemTray();

		// Create a popup menu components
		MenuItem reloadConfig = new MenuItem("Reload config");
		MenuItem getConfig = new MenuItem("Get config");
		MenuItem exit = new MenuItem("Exit");

		// Add components to popup menu
		popup.add(getConfig);
		popup.add(reloadConfig);
		popup.add(exit);

		trayIcon.setPopupMenu(popup);

		try {
			tray.add(trayIcon);
		} catch (AWTException e) {
			System.out.println("TrayIcon could not be added.");
			return;
		}

		trayIcon.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JOptionPane.showMessageDialog(null,
						"This dialog box is run from System Tray");
			}
		});

		reloadConfig.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Configurator c = new Configurator(Communicator
						.getXmlConfigPath());
				Communicator.init(c);
				Communicator.setContinCycle(false);
			}
		});

		getConfig.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Configurator c = new Configurator(Communicator
						.getXmlConfigPath());
				JOptionPane.showMessageDialog(null,
						"Port=" + c.getPort() + "\n" + "Server status="
								+ Communicator.getWebServerMode());
			}
		});

		exit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				tray.remove(trayIcon);
				System.out.println("Exit");
				TaskFinder.setTaskFinderMode(false);
				System.exit(0);
			}
		});
	}

	// Obtain the image URL
	protected static Image createImage(String path, String description) {
		URL imageURL = Tray.class.getResource(path);

		if (imageURL == null) {
			System.err.println("Resource not found: " + path);
			return null;
		} else {
			return (new ImageIcon(imageURL, description)).getImage();
		}
	}
}
